package com.iteaj.network.test.server.line;

import com.iteaj.network.AbstractProtocol;
import com.iteaj.network.config.DeviceProperties;
import com.iteaj.network.server.component.LineBasedFrameDecoderComponentAdapter;
import com.iteaj.network.server.protocol.HeartProtocol;
import com.iteaj.network.test.TestProtocolType;
import com.iteaj.network.test.message.TMessageHead;
import com.iteaj.network.test.server.line.protocol.LineDeviceRequestProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

/**
 * 测试基于换行符的解码器组件
 * @see com.iteaj.network.server.component.LineBasedFrameDecoderComponentAdapter
 */
public class LineBasedFrameDecoderTestComponent extends LineBasedFrameDecoderComponentAdapter<LineTestMessage> {

    public LineBasedFrameDecoderTestComponent(DeviceProperties deviceProperties) {
        super(deviceProperties, 1024);
    }

    @Override
    public AbstractProtocol getProtocol(LineTestMessage message) {
        TMessageHead head = message.getHead();
        // 心跳报文
        if(head.getTradeType() == TestProtocolType.Heart) {
            return HeartProtocol.getInstance(message);

            // 此请求属于客户端响应平台
        } else  if(head.getTradeType() == TestProtocolType.PIReq) {
            return remove(head.getMessageId());

            // 客户端主动请求平台的协议
        } else {
            return new LineDeviceRequestProtocol(message);
        }
    }

    @Override
    public String desc() {
        return "基于换行符实现的解码器组件测试[LineBasedFrameDecoder]";
    }

    @Override
    public String name() {
        return "换行符解码组件";
    }

    @Override
    public LineTestMessage decode(ChannelHandlerContext ctx, ByteBuf in) {
        final int readableBytes = in.readableBytes();
        byte[] message = new byte[readableBytes];

        in.readBytes(message);
        return new LineTestMessage(message);
    }
}
